import React from "react";
import "./index.less";
import classnames from "classnames";
import { directiveEnum } from "../index";
import _EE_ from "../EventEmitter";
import SubTool from "./SubTool";
import { toolsList } from "./toolList";
import { Upload } from "antd";
export type propsTypes = {
  directive?: directiveEnum;
};

export type toolsListT = {
  icon: any;
  type: string;
  subTool?: toolsListT[];
};
function Tools({ directive }: propsTypes) {
  const handleToolItem = (item: toolsListT) => {
    if (directive !== item.type) {
      let type = item.type;
      if (item.type === "pen") {
        type = "pencil";
      }

      _EE_.emit("_set_directive", type);
    }
  };
  const penFlag = ["pencil", "markPen", "eraser"].includes(directive as string);
  const graphFlag = ["graph"].includes(directive as string);
  //上传图片
  const uploadProps = {
    name: "file",
    showUploadList: false,
    beforeUpload: (file: any) => {
      if (file) {
        const reader = new FileReader();
        reader.onload = (e: any) => {
          _EE_.emit("_fabric_add_image_", e.target.result);
          _EE_.emit("_set_directive", "image");
        };
        reader.readAsDataURL(file);
      }
      return false;
    },
  };
  return (
    <div className="tool-box">
      {toolsList.map((item: toolsListT, key) => (
        <div
          key={key}
          className={classnames("tool-item", {
            active: directive === item.type || (item.type === "pen" && penFlag),
          })}
          onClick={() => handleToolItem(item)}
        >
          {item.type === "image" ? (
            <Upload {...uploadProps}>
              <img src={item.icon} />
            </Upload>
          ) : (
            <img src={item.icon} />
          )}
          <SubTool
            className={item.type === "pen" && penFlag ? "subpen" : "subpen-hidden"}
            penItem={item.subTool}
            directive={directive}
          />
          <SubTool
            className={item.type === "graph" && graphFlag ? "subpen" : "subpen-hidden"}
            penItem={item.subTool}
            directive={directive}
          />
        </div>
      ))}
    </div>
  );
}

export default Tools;
